package com.cloud.lan.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.lan.api.dto.req.LanSmsSendReq;
import com.cloud.lan.api.dto.req.LanTagCfgReq;
import com.cloud.lan.api.dto.req.SmsTemplateReq;
import com.cloud.lan.api.dto.req.SubmailTaskReq;
import com.cloud.lan.api.dto.resp.MmsTemplateResp;
import com.cloud.lan.api.dto.resp.SmsMmsModel;
import com.cloud.lan.api.dto.resp.SmsTemplateResp;
import com.cloud.lan.dao.LanSmsSendRecordMapper;
import com.cloud.lan.entity.base.BaseResponse;
import com.cloud.lan.entity.base.ListResponse;
import com.cloud.lan.entity.constant.TagConstant;
import com.cloud.lan.entity.model.dataobject.LanSmsSendRecordDO;
import com.cloud.lan.entity.model.dataobject.LanTagCfgDO;
import com.cloud.lan.entity.model.dataobject.LanUserDO;
import com.cloud.lan.entity.model.dataobject.SubmailTaskRecordDO;
import com.cloud.lan.integration.submail.mms.entity.MmsSendReq;
import com.cloud.lan.integration.submail.mms.entity.MmsSendRes;
import com.cloud.lan.integration.submail.mms.entity.MmsTemplateModel;
import com.cloud.lan.integration.submail.mms.service.MmsSendService;
import com.cloud.lan.integration.submail.sms.entity.SmsSendModel;
import com.cloud.lan.integration.submail.sms.entity.SmsSendReq;
import com.cloud.lan.integration.submail.sms.entity.SmsSendRes;
import com.cloud.lan.integration.submail.sms.service.SmsSendService;
import com.cloud.lan.service.ILanSmsSendService;
import com.cloud.lan.service.ILanTagCfgService;
import com.cloud.lan.service.ILanTagUserService;
import com.cloud.lan.service.ISubmailTaskService;
import com.cloud.lan.service.sms.MmsTemplateManageService;
import com.cloud.lan.service.sms.SmsTemplateManageService;
import com.cloud.lan.service.tx.wx.WxCService;
import com.cloud.lan.service.tx.wx.model.WxUrlLinkReq;
import com.cloud.lan.service.tx.wx.model.WxUrlLinkRes;
import com.cloud.lan.util.LanDateUtils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by zhouquan on 2022/4/14.
 */
@Slf4j
@Service
public class LanSmsSendServiceImpl extends ServiceImpl<LanSmsSendRecordMapper, LanSmsSendRecordDO> implements ILanSmsSendService{

    @Resource
    private LanSmsSendRecordMapper lanSmsSendRecordMapper;
    @Autowired
    private ILanTagCfgService iLanTagCfgService;
    @Autowired
    private SmsTemplateManageService manageService;
    @Autowired
    private MmsTemplateManageService mmsTemplateManageService;
    @Autowired
    private ILanTagUserService iLanTagUserService;
    @Autowired
    private SmsSendService smsSendService;
    @Autowired
    private WxCService wxCService;
    @Autowired
    private MmsSendService mmsSendService;
    @Autowired
    private ISubmailTaskService submailTaskService;

    private ExecutorService executorService = Executors.newFixedThreadPool(1);

    private ExecutorService executorService2 = Executors.newFixedThreadPool(5);

    private int pageSize = 40;
    private static final String LANMPURL = "lanMpUrl";//兰嘉丝汀小程序链接

    @Override
    public BaseResponse<Object> submitTask(LanSmsSendReq sendReq) {
        log.info("发送短信.新建任务.req:[{}]",JSON.toJSONString(sendReq));
        //参数校验
        if(StringUtils.isAnyBlank(sendReq.getTemplateId(),sendReq.getTagCodes())){
            return BaseResponse.error(BaseResponse.ERROR,"参数缺失");
        }

        SmsMmsModel smsMmsModel = new SmsMmsModel();
        //短信模板ID校验
        if(StringUtils.isNotBlank(sendReq.getTemplateId())
                && StringUtils.equals("1",sendReq.getTemplateType())){
            SmsTemplateReq templateReq = new SmsTemplateReq();
            templateReq.setTemplateId(sendReq.getTemplateId());
            ListResponse<List<SmsTemplateResp>> listResponse = manageService.manageList(templateReq);
            if(Objects.isNull(listResponse) || CollectionUtils.isEmpty(listResponse.getData())){
                return BaseResponse.error(BaseResponse.ERROR,"短信模板不存在");
            }
            SmsTemplateResp templateResp = listResponse.getData().get(0);
            if(!StringUtils.equalsIgnoreCase("2",templateResp.getTemplateStatus())){
                return BaseResponse.error(BaseResponse.ERROR,"短信模板不是审核通过状态");
            }
            smsMmsModel.setSmsTemplateResp(templateResp);
        }else if(StringUtils.isNotBlank(sendReq.getTemplateId())
                && StringUtils.equals("2",sendReq.getTemplateType())){//彩信模板ID校验
            MmsTemplateModel mmsTemplateModel = new MmsTemplateModel();
            mmsTemplateModel.setTemplateId(sendReq.getTemplateId());
            ListResponse<List<MmsTemplateResp>> mmsTR = mmsTemplateManageService.manageList(mmsTemplateModel);
            if(Objects.isNull(mmsTR) || CollectionUtils.isEmpty(mmsTR.getData())){
                return BaseResponse.error(BaseResponse.ERROR,"彩信模板不存在");
            }
            MmsTemplateResp mmsTemplateResp = mmsTR.getData().get(0);
            if(!StringUtils.equalsIgnoreCase("2",mmsTemplateResp.getTemplateStatus())){
                return BaseResponse.error(BaseResponse.ERROR,"彩信模板不是审核通过状态");
            }
            smsMmsModel.setMmsTemplateResp(mmsTemplateResp);
        }
        if(Objects.isNull(smsMmsModel.getSmsTemplateResp()) && Objects.isNull(smsMmsModel.getMmsTemplateResp())){
            return BaseResponse.error(BaseResponse.ERROR,"模板不存在");
        }
        sendReq.setSmsMmsModel(smsMmsModel);

        //标签配置查询
        LanTagCfgReq cfgReq = new LanTagCfgReq();
        cfgReq.setTagCodes(sendReq.getTagCodes());
        ListResponse<List<LanTagCfgDO>> tagCfgListResp = iLanTagCfgService.queryTagCfgList(cfgReq);
        List<LanTagCfgDO> tagCfgDOList = tagCfgListResp.getData();
        if(CollectionUtils.isEmpty(tagCfgDOList)){
            return BaseResponse.error(BaseResponse.ERROR,"标签配置不存在");
        }

        //是否存在未结束的任务
        SubmailTaskReq taskReq = new SubmailTaskReq();
        taskReq.setTemplateId(sendReq.getTemplateId());
        taskReq.setTagCode(sendReq.getTagCodes());
        boolean hasExistHandingTask = submailTaskService.hasExistHandingTask(taskReq);
        if(hasExistHandingTask){
            log.warn("该短信模板和标签存在未处理完的任务.req:[{}]",JSON.toJSONString(sendReq));
            return BaseResponse.error(BaseResponse.ERROR,"该短信模板和标签存在未处理完的任务");
        }

        //初始化短信发送任务
        SubmailTaskRecordDO taskRecordDO = buildSubmailTaskRecordDO(sendReq,tagCfgDOList.get(0),smsMmsModel);
        submailTaskService.merge(taskRecordDO);

        log.info("发送短信.新建任务.end");
        return BaseResponse.success();
    }

    private SubmailTaskRecordDO buildSubmailTaskRecordDO(LanSmsSendReq sendReq,LanTagCfgDO tagCfgDO,SmsMmsModel smsMmsModel){
        SubmailTaskRecordDO recordDO = new SubmailTaskRecordDO();
        if(StringUtils.isNoneBlank(sendReq.getTemplateId(),sendReq.getTemplateType())){
            recordDO.setTemplateId(sendReq.getTemplateId());
            recordDO.setTemplateType(Integer.parseInt(sendReq.getTemplateType()));
            if(StringUtils.equals("1",sendReq.getTemplateType()) && Objects.nonNull(smsMmsModel.getSmsTemplateResp())){
                recordDO.setTemplateTitle(smsMmsModel.getSmsTemplateResp().getSmsTitle());
            }else if(StringUtils.equals("2",sendReq.getTemplateType()) && Objects.nonNull(smsMmsModel.getMmsTemplateResp())){
                recordDO.setTemplateTitle(smsMmsModel.getMmsTemplateResp().getMmsTitle());
            }
            if(Objects.nonNull(sendReq.getVars()) && sendReq.getVars().size()>0){
                recordDO.setTemplateParams(JSON.toJSONString(sendReq.getVars()));
            }
        }
        recordDO.setTagCode(sendReq.getTagCodes());
        recordDO.setTagDesc(tagCfgDO.getTagName());
        recordDO.setTaskStatus(1);
        int totalCount = iLanTagUserService.queryTagUserNums(tagCfgDO);
        recordDO.setTotalNums(totalCount);
        return recordDO;
    }


    @Override
    public BaseResponse<Object> initTaskRecordData(Long taskId) {
        log.info("taskId:[{}] 初始化任务发送数据.start",taskId);
        SubmailTaskRecordDO recordDO = submailTaskService.queryById(taskId);
        if(Objects.isNull(recordDO)){
            BaseResponse baseResponse = BaseResponse.error("SUB023",taskId+"该任务不存在");
            return baseResponse;
        }

        LanSmsSendReq sendReq = buildLanSmsSendReqByTaskRecord(recordDO);
        if(Objects.isNull(sendReq.getSmsMmsModel())){
            BaseResponse baseResponse = BaseResponse.error("SUB023",taskId+"模板不存在");
            return baseResponse;
        }

        //标签配置查询
        LanTagCfgReq cfgReq = new LanTagCfgReq();
        cfgReq.setTagCodes(sendReq.getTagCodes());
        ListResponse<List<LanTagCfgDO>> tagCfgListResp = iLanTagCfgService.queryTagCfgList(cfgReq);
        List<LanTagCfgDO> tagCfgDOList = tagCfgListResp.getData();
        if(CollectionUtils.isEmpty(tagCfgDOList)){
            BaseResponse baseResponse = BaseResponse.error("SUB023",taskId+"标签配置不存在");
            return baseResponse;
        }

        executorService.execute(()->{
            handleInitTaskRecordData(sendReq,tagCfgDOList.get(0));
        });


        log.info("taskId:[{}] 初始化任务发送数据.end",taskId);
        BaseResponse baseResponse = BaseResponse.success();
        return baseResponse;
    }


    private LanSmsSendReq buildLanSmsSendReqByTaskRecord(SubmailTaskRecordDO recordDO){
        LanSmsSendReq sendReq = new LanSmsSendReq();
        sendReq.setTaskId(recordDO.getId());
        sendReq.setTemplateId(recordDO.getTemplateId());
        sendReq.setTagCodes(recordDO.getTagCode());
        sendReq.setTemplateType(recordDO.getTemplateType()+"");
        if(StringUtils.isNoneBlank(recordDO.getTemplateParams())){
            sendReq.setVars(JSON.parseObject(recordDO.getTemplateParams(),Map.class));
        }

        SmsMmsModel smsMmsModel = new SmsMmsModel();
        //短信模板ID校验
        if(StringUtils.isNotBlank(recordDO.getTemplateId())
                && StringUtils.equals("1",recordDO.getTemplateType()+"")){
            SmsTemplateReq templateReq = new SmsTemplateReq();
            templateReq.setTemplateId(recordDO.getTemplateId());
            ListResponse<List<SmsTemplateResp>> listResponse = manageService.manageList(templateReq);
            if(Objects.nonNull(listResponse)
                    && CollectionUtils.isNotEmpty(listResponse.getData())){
                SmsTemplateResp templateResp = listResponse.getData().get(0);
                if(StringUtils.equalsIgnoreCase("2",templateResp.getTemplateStatus())){
                    smsMmsModel.setSmsTemplateResp(templateResp);
                }
            }
        }else if(StringUtils.isNotBlank(recordDO.getTemplateId())
                && StringUtils.equals("2",recordDO.getTemplateType()+"")){//彩信模板ID校验
            MmsTemplateModel mmsTemplateModel = new MmsTemplateModel();
            mmsTemplateModel.setTemplateId(recordDO.getTemplateId());
            ListResponse<List<MmsTemplateResp>> mmsTR = mmsTemplateManageService.manageList(mmsTemplateModel);
            if(Objects.nonNull(mmsTR) && CollectionUtils.isNotEmpty(mmsTR.getData())){
                MmsTemplateResp mmsTemplateResp = mmsTR.getData().get(0);
                if(StringUtils.equalsIgnoreCase("2",mmsTemplateResp.getTemplateStatus())){
                    smsMmsModel.setMmsTemplateResp(mmsTemplateResp);
                }
            }

        }
        if(Objects.nonNull(smsMmsModel.getSmsTemplateResp()) || Objects.nonNull(smsMmsModel.getMmsTemplateResp())){
            sendReq.setSmsMmsModel(smsMmsModel);
        }
        sendReq.setSmsMmsModel(smsMmsModel);
        return sendReq;
    }

    private void handleInitTaskRecordData(LanSmsSendReq sendReq, LanTagCfgDO cfg){
        log.info("发送短信.初始化任务数据.start.sendReq:[{}]---cfg:[{}]",JSON.toJSONString(sendReq),JSON.toJSONString(cfg));
        //任务状态--数据初始化中
        SubmailTaskRecordDO upd = new SubmailTaskRecordDO();
        upd.setId(sendReq.getTaskId());
        upd.setTaskStatus(2);
        submailTaskService.merge(upd);

        SmsMmsModel smsMmsModel = sendReq.getSmsMmsModel();
        Date tody = LanDateUtils.getTodayStartDate();
        //落发送记录初始化表
        //标签人群查询
        AtomicInteger atomicInteger = new AtomicInteger(1);
        List<Future> futureList = new ArrayList<>();
        int totalCount = iLanTagUserService.totalCount(cfg);
        int totalPage = getTotalPages(totalCount);
        for(int j=0;j<=totalPage;j++){
            Future fu = executorService2.submit(()->{
                List<LanUserDO> userDOS = iLanTagUserService.queryUserByTag(cfg,atomicInteger.getAndIncrement());

                if(CollectionUtils.isEmpty(userDOS)){
                    userDOS = new ArrayList<>();
                }
                log.info("发送短信.落发送记录初始化表.查询到用户数:[{}]",userDOS.size());
                //发送记录初始化
                userDOS.stream().forEach(usr->{
                    LanSmsSendRecordDO recordDO = new LanSmsSendRecordDO();
                    try{
                        recordDO.setTaskId(sendReq.getTaskId());
                        recordDO.setUserId(usr.getUserId());
                        recordDO.setMobile(usr.getUserPhone());
                        recordDO.setTemplateType(sendReq.getTemplateType());
                        if(StringUtils.equals("1",recordDO.getTemplateType())){
                            recordDO.setTemplateId(smsMmsModel.getSmsTemplateResp().getTemplateId());
                        }else if(StringUtils.equals("2",recordDO.getTemplateType())){
                            recordDO.setTemplateId(smsMmsModel.getMmsTemplateResp().getTemplateId());
                        }

                        recordDO.setTagCode(cfg.getTagCode());
                        recordDO.setSendStatus(1);
                        Date now = new Date();
                        recordDO.setSendTime(DateUtils.addMinutes(now,-10));
                        recordDO.setCreateTime(now);
                        recordDO.setUpdateTime(now);
                        if(StringUtils.equals("1",recordDO.getTemplateType())){
                            recordDO.setSmsContent(smsMmsModel.getSmsTemplateResp().getSmsSignature()+" "+smsMmsModel.getSmsTemplateResp().getSmsContent());
                        }
//                        else if(StringUtils.equals("2",recordDO.getTemplateType()) && Objects.nonNull(smsMmsModel.getMmsTemplateResp())
//                                && CollectionUtils.isNotEmpty(smsMmsModel.getMmsTemplateResp().getContentList())){
//                            recordDO.setSmsContent(smsMmsModel.getMmsTemplateResp().getMmsSignature()+" "+smsMmsModel.getMmsTemplateResp().getContentList().get(0).getText());
//                        }

                        if(Objects.nonNull(sendReq.getVars()) && sendReq.getVars().size()>0){
                            recordDO.setSmsParams(JSON.toJSONString(sendReq.getVars()));
                        }

                        if(StringUtils.equalsIgnoreCase(cfg.getTagCode(),"tagyanshou")){
                            lanSmsSendRecordMapper.insert(recordDO);
                        }else{
                            //判断用户当天是否发送过
                            LambdaQueryWrapper<LanSmsSendRecordDO> qw = new LambdaQueryWrapper<>();
                            qw.eq(LanSmsSendRecordDO::getUserId,recordDO.getUserId());
                            qw.eq(LanSmsSendRecordDO::getTemplateId,sendReq.getTemplateId());
                            qw.in(LanSmsSendRecordDO::getSendStatus, Arrays.asList(1,2,3));
                            qw.ge(LanSmsSendRecordDO::getCreateTime,tody);
                            qw.eq(LanSmsSendRecordDO::getIsDeleted,0);
                            long i = lanSmsSendRecordMapper.selectCount(qw);
                            if(i==0){
                                log.info("userId:[{}] 发送短信.当天该模板发送记录不重复提交.模板ID:[{}]",recordDO.getUserId(),sendReq.getTemplateId());
                                lanSmsSendRecordMapper.insert(recordDO);
                            }
                        }
                    }catch (Exception e){
                        log.error("record:[{}] 发送短信.初始化任务数据.失败",JSON.toJSONString(recordDO),e);
                    }

                });
            });
            futureList.add(fu);
        }
        futureList.stream().forEach(future -> {
            try {
                future.get();
            }catch (Exception e){
                log.info("发送短信.并发初始化任务数据异常",e);
            }
        });
        //任务状态--数据初始化完成
        upd = new SubmailTaskRecordDO();
        upd.setId(sendReq.getTaskId());
        upd.setTaskStatus(3);
        submailTaskService.merge(upd);
        log.info("发送短信.初始化任务数据.end");
    }




    private int getTotalPages(int totalCount) {
        if(totalCount == 0L) {
            return 0;
        } else {
            int pages = totalCount / TagConstant.TAG_USER_PAGESIZE;
            if(totalCount % TagConstant.TAG_USER_PAGESIZE != 0L) {
                ++pages;
            }
            log.info("总记录数:[{}] 发送短信.总页数:[{}]",totalCount,pages);
            return pages;
        }
    }


    @Override
    public BaseResponse<Object> applySend(Long taskId) {
        log.info("taskId:[{}] 发送短信.start",taskId);

        SubmailTaskRecordDO recordDO = submailTaskService.queryById(taskId);
        if(Objects.isNull(recordDO)){
            BaseResponse baseResponse = BaseResponse.error("SUB023",taskId+"该任务不存在");
            return baseResponse;
        }

        LanSmsSendReq sendReq = buildLanSmsSendReqByTaskRecord(recordDO);
        if(Objects.isNull(sendReq.getSmsMmsModel())){
            BaseResponse baseResponse = BaseResponse.error("SUB023",taskId+"模板不存在");
            return baseResponse;
        }


        sendReq.setTaskId(taskId);
        executorService.execute(()->{
            handleSend(sendReq);
        });

        BaseResponse baseResponse = BaseResponse.success();
        log.info("taskId:[{}] 发送短信.end",taskId);
        return baseResponse;
    }

    public BaseResponse handleSend(LanSmsSendReq sendReq){
        log.info("发送短信.发送.req:[{}]",JSON.toJSONString(sendReq));
        //任务状态--submail发送中
        SubmailTaskRecordDO upd = new SubmailTaskRecordDO();
        upd.setId(sendReq.getTaskId());
        upd.setTaskStatus(4);
        submailTaskService.merge(upd);

        //取大于发送时间.sendStatus==1的
        LambdaQueryWrapper<LanSmsSendRecordDO> qw = new LambdaQueryWrapper<>();
        //qw.eq(LanSmsSendRecordDO::getSendStatus,1);
        qw.eq(LanSmsSendRecordDO::getTaskId,sendReq.getTaskId());
        //qw.le(LanSmsSendRecordDO::getSendTime,new Date());
        qw.eq(LanSmsSendRecordDO::getIsDeleted,0);
        int totalSize = lanSmsSendRecordMapper.selectCount(qw);
        long totalPages = getTotalPages(pageSize,totalSize);
        log.info("短信记录表.待发送总数:[{}]----循环次数:[{}]",totalSize,totalPages);
        for(int num =1;num<=totalPages;num++){
            log.info("短信记录表.待发送总数:[{}]----循环第[{}]次",totalSize,num);
            try{
                Page<LanSmsSendRecordDO> page = new Page<>(num, pageSize);
                IPage<LanSmsSendRecordDO> pageList = lanSmsSendRecordMapper.selectPage(page, qw);
                if(Objects.nonNull(pageList) && CollectionUtils.isNotEmpty(pageList.getRecords())){
                    List<LanSmsSendRecordDO> recordDOS = pageList.getRecords().stream().filter(rd->rd.getSendStatus() ==1 || rd.getSendStatus() ==2).collect(Collectors.toList());
                    executorService2.execute(()->{
                        if(StringUtils.equals("1",sendReq.getTemplateType())){
                            doSend(sendReq,recordDOS);
                        }else if(StringUtils.equals("2",sendReq.getTemplateType())){
                            doMmsSend(sendReq,recordDOS);
                        }
                    });
                }

            }catch (Exception e){
                log.error("发送短信.批量发送异常",e);
            }
        }

        while (hasNotHandleSmsRecords(sendReq.getTaskId())){
            sleep2min();
        }

        //任务状态--submail发送结束
        upd = new SubmailTaskRecordDO();
        upd.setId(sendReq.getTaskId());
        upd.setTaskStatus(5);
        upd.setSendSucNums(sucNums(sendReq.getTaskId()));
        upd.setSendFailNums(failNums(sendReq.getTaskId()));
        submailTaskService.merge(upd);

        log.info("发送短信.发送.end");
        return BaseResponse.success();
    }

    private boolean hasNotHandleSmsRecords(Long taskId){
        LambdaQueryWrapper<LanSmsSendRecordDO> qw = new LambdaQueryWrapper<>();
        qw.in(LanSmsSendRecordDO::getSendStatus,Arrays.asList(1,2));
        qw.eq(LanSmsSendRecordDO::getTaskId,taskId);
        int totalSize = lanSmsSendRecordMapper.selectCount(qw);
        return totalSize>0;
    }

    private int sucNums(Long taskId){
        LambdaQueryWrapper<LanSmsSendRecordDO> qw = new LambdaQueryWrapper<>();
        qw.eq(LanSmsSendRecordDO::getSendStatus,3);
        qw.eq(LanSmsSendRecordDO::getTaskId,taskId);
        return lanSmsSendRecordMapper.selectCount(qw);
    }

    private int failNums(Long taskId){
        LambdaQueryWrapper<LanSmsSendRecordDO> qw = new LambdaQueryWrapper<>();
        qw.eq(LanSmsSendRecordDO::getSendStatus,4);
        qw.eq(LanSmsSendRecordDO::getTaskId,taskId);
        return lanSmsSendRecordMapper.selectCount(qw);
    }

    private void doSend(LanSmsSendReq sendReq,List<LanSmsSendRecordDO> recordDOS){
        if(CollectionUtils.isEmpty(recordDOS)){
            log.warn("submail不发送.短信记录表数据空");
            return;
        }


        SmsTemplateResp smsTemplateResp = sendReq.getSmsMmsModel().getSmsTemplateResp();
        if(Objects.isNull(smsTemplateResp)){
            log.warn("submail不发送.短信模板不存在");
            return;
        }
        //发送请求
        SmsSendReq smsSendReq = new SmsSendReq();
        smsSendReq.setTemplateId(smsTemplateResp.getTemplateId());
        List<SmsSendModel> modelList = new ArrayList<>();
        smsSendReq.setModelList(modelList);

        //发送中
        recordDOS.stream().forEach(rd->{
            LanSmsSendRecordDO upd = new LanSmsSendRecordDO();
            upd.setId(rd.getId());
            upd.setSendStatus(2);
            lanSmsSendRecordMapper.updateById(upd);

            SmsSendModel smsSendModel = new SmsSendModel();
            smsSendModel.setTemplateId(smsTemplateResp.getTemplateId());
            smsSendModel.setTo(rd.getMobile());
            Map<String,String> vars = JSON.parseObject(rd.getSmsParams(), Map.class);
            //如果短信模板里有lanMpUrl参数---则是生成小程序链接
            boolean needSend = true;
            String errorMsg = null;
            String errorCode = null;
            if(StringUtils.isNotBlank(smsTemplateResp.getSmsContent())
                    && smsTemplateResp.getSmsContent().contains(LANMPURL)){
                WxUrlLinkReq linkReq = new WxUrlLinkReq();
                if(Objects.nonNull(vars) && vars.containsKey(LANMPURL)
                        && StringUtils.isNotBlank(vars.get(LANMPURL))){
                    linkReq.setPath(vars.get(LANMPURL));
                }
                WxUrlLinkRes linkRes = wxCService.createUrlLink(linkReq);
                if(StringUtils.isBlank(linkRes.getUrl_link())){
                    needSend = false;
                    errorCode = linkRes.getErrcode();
                    errorMsg = linkRes.getErrmsg();
                    log.error("userId:[{}] submail不发送.短信微信urllink生成失败",rd.getUserId());
                }else{
                    vars.put(LANMPURL,linkRes.getUrl_link());
                }
            }
            //如果短信模板有lanMpUrl.但是wx的urllink生成失败.则不发短信
            if(needSend){
                smsSendModel.setVars(vars);
                modelList.add(smsSendModel);
            }else{
                upd.setSendStatus(4);
                upd.setResCode(errorCode);
                upd.setResMsg("微信的urllink生成失败");
                if(StringUtils.isNotBlank(errorMsg)){
                    upd.setResMsg(errorMsg);
                }
                lanSmsSendRecordMapper.updateById(upd);
            }
        });
        if(CollectionUtils.isEmpty(smsSendReq.getModelList())){
            log.warn("submail不发送.短信无指定手机号不发送");
            return;
        }
        //批量发送
        log.info("短信记录表.批量发送.req:[{}]",JSON.toJSONString(smsSendReq));
        List<SmsSendRes> resList = smsSendService.multixsend(smsSendReq);
        log.info("短信记录表.批量发送.res:[{}]",JSON.toJSONString(resList));
//        sleep200ms();
//        List<SmsSendRes> resList = new ArrayList<>();
//        recordDOS.stream().forEach(rd->{
//            SmsSendRes smsSendRes = new SmsSendRes();
//            smsSendRes.setTo(rd.getMobile());
//            smsSendRes.setSendId("mock"+rd.getId());
//            smsSendRes.setCode("smscode");
//            smsSendRes.setMsg("smsmockmsg");
//            smsSendRes.setStatus("success");
//            resList.add(smsSendRes);
//        });
        if(CollectionUtils.isNotEmpty(resList)){
            resList.stream().forEach(ssr->{
                String mobile = ssr.getTo();
                recordDOS.stream().filter(rd->StringUtils.equalsIgnoreCase(mobile,rd.getMobile())).forEach(rs->{
                    LanSmsSendRecordDO upd = new LanSmsSendRecordDO();
                    upd.setId(rs.getId());
                    upd.setOuterSendId(ssr.getSendId());
                    upd.setResCode(ssr.getCode());
                    upd.setResMsg(ssr.getMsg());
                    if(StringUtils.equalsIgnoreCase("success",ssr.getStatus())){
                        upd.setSendStatus(3);
                    }else{
                        upd.setSendStatus(4);
                    }
                    lanSmsSendRecordMapper.updateById(upd);
                });
            });
        }
    }


    private void doMmsSend(LanSmsSendReq sendReq,List<LanSmsSendRecordDO> recordDOS){
        if(CollectionUtils.isEmpty(recordDOS)){
            log.warn("submail不发送.彩信记录表数据空");
            return;
        }


        MmsTemplateResp mmsTemplateResp = sendReq.getSmsMmsModel().getMmsTemplateResp();
        if(Objects.isNull(mmsTemplateResp)){
            log.warn("submail不发送.彩信模板不存在");
            return;
        }

        //发送请求
        MmsSendReq smsSendReq = new MmsSendReq();
        smsSendReq.setTemplateId(mmsTemplateResp.getTemplateId());
        List<SmsSendModel> modelList = new ArrayList<>();
        smsSendReq.setModelList(modelList);

        //boolean hasLANMPURL = mmsTemplateResp.getContentList().stream().filter(co->co.getText().contains(LANMPURL)).count()>0;

        boolean hasLANMPURL = false;

        //发送中
        recordDOS.stream().forEach(rd->{
            LanSmsSendRecordDO upd = new LanSmsSendRecordDO();
            upd.setId(rd.getId());
            upd.setSendStatus(2);
            lanSmsSendRecordMapper.updateById(upd);

            SmsSendModel smsSendModel = new SmsSendModel();
            smsSendModel.setTemplateId(mmsTemplateResp.getTemplateId());
            smsSendModel.setTo(rd.getMobile());
            Map<String,String> vars = JSON.parseObject(rd.getSmsParams(), Map.class);
            //如果短信模板里有lanMpUrl参数---则是生成小程序链接
            boolean needSend = true;
            String errorMsg = null;
            String errorCode = null;
            if(hasLANMPURL){
                WxUrlLinkReq linkReq = new WxUrlLinkReq();
                if(Objects.nonNull(vars) && vars.containsKey(LANMPURL)
                        && StringUtils.isNotBlank(vars.get(LANMPURL))){
                    linkReq.setPath(vars.get(LANMPURL));
                }
                WxUrlLinkRes linkRes = wxCService.createUrlLink(linkReq);
                if(StringUtils.isBlank(linkRes.getUrl_link())){
                    needSend = false;
                    errorCode = linkRes.getErrcode();
                    errorMsg = linkRes.getErrmsg();
                    log.error("userId:[{}] submail不发送.微信urllink生成失败",rd.getUserId());
                }else{
                    vars.put(LANMPURL,linkRes.getUrl_link());
                }
            }
            //如果短信模板有lanMpUrl.但是wx的urllink生成失败.则不发短信
            if(needSend){
                smsSendModel.setVars(vars);
                modelList.add(smsSendModel);
            }else{
                upd.setSendStatus(4);
                upd.setResCode(errorCode);
                upd.setResMsg("微信的urllink生成失败");
                if(StringUtils.isNotBlank(errorMsg)){
                    upd.setResMsg(errorMsg);
                }
                lanSmsSendRecordMapper.updateById(upd);
            }
        });
        if(CollectionUtils.isEmpty(smsSendReq.getModelList())){
            log.warn("submail不发送.彩信无指定手机号不发送");
            return;
        }
        //批量发送
        log.info("短信记录表.批量发送彩信.req:[{}]",JSON.toJSONString(smsSendReq));
        List<MmsSendRes> resList = mmsSendService.multixsend(smsSendReq);
        log.info("短信记录表.批量发送彩信.res:[{}]",JSON.toJSONString(resList));
//        sleep200ms();
//        List<MmsSendRes> resList = new ArrayList<>();
//        recordDOS.stream().forEach(rd->{
//            MmsSendRes smsSendRes = new MmsSendRes();
//            smsSendRes.setTo(rd.getMobile());
//            smsSendRes.setSendId("mock"+rd.getId());
//            smsSendRes.setCode("mmscode");
//            smsSendRes.setMsg("mmsmockmsg");
//            smsSendRes.setStatus("success");
//            resList.add(smsSendRes);
//        });
        if(CollectionUtils.isNotEmpty(resList)){
            resList.stream().forEach(ssr->{
                String mobile = ssr.getTo();
                recordDOS.stream().filter(rd->StringUtils.equalsIgnoreCase(mobile,rd.getMobile())).forEach(rs->{
                    LanSmsSendRecordDO upd = new LanSmsSendRecordDO();
                    upd.setId(rs.getId());
                    upd.setOuterSendId(ssr.getSendId());
                    upd.setResCode(ssr.getCode());
                    upd.setResMsg(ssr.getMsg());
                    if(StringUtils.equalsIgnoreCase("success",ssr.getStatus())){
                        upd.setSendStatus(3);
                    }else{
                        upd.setSendStatus(4);
                    }
                    lanSmsSendRecordMapper.updateById(upd);
                });
            });
        }
    }

    private long getTotalPages(int pageSize,int totalSize){
        long pages = totalSize / pageSize;
        if(totalSize % pageSize != 0L) {
            ++pages;
        }
        return pages;
    }

    private void sleep200ms(){
        try{
            Thread.sleep(200);
        }catch (Exception e){
            log.error("线程模拟sleep异常",e);
        }
    }

    private void sleep2min(){
        try{
            Thread.sleep(1000*60*2);
        }catch (Exception e){
            log.error("线程模拟sleep异常",e);
        }
    }

}
